package book.read;

import java.io.IOException;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import oracle.net.aso.i;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;

import book.dao.impl.BookDaoImpl;
import book.pojo.Book;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class BookReadThread implements Runnable {

	public void run() {
		// TODO Auto-generated method stub
		long start=System.currentTimeMillis();
		ConnectionFactory factory=new ActiveMQConnectionFactory("tcp://10.222.29.152:61616");
		Destination queueDestination=new ActiveMQQueue("books");
		Connection connection = null;
		Session session=null;
		MessageConsumer mc=null;
		try {
			connection = factory.createConnection();
			connection.start();
			session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			mc=session.createConsumer(queueDestination);
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		BookDaoImpl bdi=new BookDaoImpl();
		final ObjectMapper oMapper=new ObjectMapper();
		
		while(BookReadMulti.i<10000)
		{
			try {
				synchronized (BookReadMulti.i) {
					TextMessage msg=(TextMessage) mc.receive();
					String temp=msg.getText();
					Book tempBook=new Book();
					tempBook=oMapper.readValue(temp, Book.class);
					bdi.addBook(tempBook);
					BookReadMulti.i++;
					msg.acknowledge();
					System.out.println(connection.toString());
				}
			} catch (JsonParseException e) {
				// TODO Auto-generated catch block
				break;
			} catch (JsonMappingException e) {
				// TODO Auto-generated catch block
				break;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				break;
			} catch (JMSException e) {
				// TODO Auto-generated catch block
				break;
			}
		}
		long end=System.currentTimeMillis();
        System.out.println("need time "+(end-start));
		try {
			mc.close();
			session.close();
			connection.close();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
